package com.dhcc.userDetailService;

import com.dhcc.entity.SysUser;
import com.dhcc.service.SysUserService;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


/**
 * 管理端用户登录认证服务实现类
 * @ProjectName Dhcc-Cloud
 * @PackageName com.dhcc.service
 * @Title CustomerUserDetailsService
 * @Date 2024/10/8 上午1:21
 * @Author LiuGuoting
 */
public class SystemUserDetailsServiceImpl implements UserDetailsService {
    private static final Logger log = LoggerFactory.getLogger(SystemUserDetailsServiceImpl.class);
    @Resource
    private SysUserService sysUserService;
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
        log.info("用户开始登录，用户名：{}", username);
        // TODO: 根据用户名查询用户信息，并返回UserDetails对象
        SysUser sysUser = sysUserService.getUserByUsername(username);
        if (sysUser == null||sysUser.getDelFlag() == 1) {
            log.error("用户不存在或已被删除！");
            return null;
        }
        // 判断用户是否被禁用
        boolean disabled = sysUser.getStatus() == 1;
        log.info("用户{}状态：{}", username, disabled? "禁用" : "启用");
        // 返回 UserDetails
        return User
                // 设置用户名，来自 sysUser 对象
                .withUsername(sysUser.getUserName())
                // 设置密码，来自 sysUser 对象
                .password(sysUser.getUserPassword())
                // 设置账户未禁用
                .disabled(disabled)
                // 设置账户未锁定
                .accountLocked(false)
                // 设置账户未过期
                .accountExpired(false)
                // 设置凭据未过期
                .credentialsExpired(false)
                .build();
    }
}
